package com.skywo.demo1.common.security

import com.skywo.demo1.service.UserService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.web.DefaultSecurityFilterChain

@Configuration
@EnableWebSecurity
class WebSecurityConfig(private val userService: UserService) {

    @Bean
    fun filterChain(http: HttpSecurity): DefaultSecurityFilterChain {
        return http
            .csrf().disable()
            .cors().and()
            .authorizeHttpRequests { authorize ->
                authorize.antMatchers("/login", "/v2/api-docs").permitAll()
                authorize.anyRequest().authenticated()
            }
            .exceptionHandling { exp ->
                exp.authenticationEntryPoint(MyAuthenticationEntryPoint())
            }
            .formLogin { form ->
                form.loginProcessingUrl("/login").permitAll()
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .failureUrl("/login/error")
                    .successHandler(MyAuthenticationSuccessHandler())
                    .failureHandler(MyAuthenticationFailureHandler())
            }
            .userDetailsService(userService)
            .logout { logout ->
                logout.logoutUrl("/user/logout").permitAll()
                    .logoutSuccessHandler(MyLogoutSuccessHandler())
            }
            .build()
    }

//    @Bean
//    fun passwordEncoder(): PasswordEncoder {
//        return BCryptPasswordEncoder()
//    }

}